import router from './router'
import store from './store'
// import axios from 'axios'
// import { Message } from 'element-ui'

const whiteList = ['/user/login'] // 不重定向白名单

router.beforeEach((to, from, next) => {
  let _token = store.state.userInfo.token
  if (_token) { // 判断是否有token
    if (to.path === '/user/login') {
      next()
    } else {
      // console.log('addrouters', store.getters.addRouters)
      // console.log(store.getters.roles)
      if (!(store.getters.isAddRouters)) { // 这里要做一下判断，否则会出现死循环
        const roles = store.state.userInfo.role // note: roles must be a array! such as: ['editor','develop']
        // console.log('roles?', roles)
        store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据roles权限生成可访问的路由表
          // console.log('addrouters', store.getters.addRouters)
          router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
          next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          console.log('路由加载完成')
        }).catch(err => {
          next({ path: '/user/login' })
          console.log(err)
        })
        console.log(store.getters.addRouters)
      } else {
        next()
      }
      // if (store.getters.roles.length === 0) {
      //   console.log('roles====0')
      //   const roles = store.state.userInfo.roleId // note: roles must be a array! such as: ['editor','develop']
      //   console.log('roles?', roles)
      //   store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据roles权限生成可访问的路由表
      //     console.log('addrouters', store.getters.addRouters)
      //     router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
      //     next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
      //   }).catch(err => {
      //     next({ path: '/login' })
      //     console.log(err)
      //   })
      // } else {
      //   console.log('====1')
      //   next() // 当有用户权限的时候，说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面
      // }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/user/login')
    }
  }
})
router.afterEach((to, from, next) => {
  let routerTitle = ''
  if (to.meta.title) {
    routerTitle = `${to.meta.title}`
  } else {
    routerTitle = 'fangcun'
  }
  document.title = routerTitle
})
